import json

from django.shortcuts import render,redirect
from django.urls import reverse
from system.models import User,Goods,Unit,GoodsType,Pic,TransactionRecords

import random
import time

#接口
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt

from system.views import SUCCESS_CODE,ERR_CODE,ERR_TIMEOUT,SUCCESS_MESSAGE,ERR_MESSAGE


# 手动添加订单
@csrf_exempt
def addOrder(request):
    dic = {}
    if request.method == 'POST':
        pass
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})


# 自动随机生成订单
@csrf_exempt
def autoAddOrder(request):
    dic = {}
    if request.method == 'POST':
        userId = request.POST.get('username')
        goodsInfo = Goods.objects.filter(isShelves=True).filter(sum__gt=0)  # 库存大于0
        if goodsInfo:
            # 随机出售商品
            item = random.randint(0, len(goodsInfo)-1)
            goods = goodsInfo[item]
            # 随机出售数量
            if goods.sum >= 5:
                sellSum = random.randint(1,5)
            else:
                sellSum = random.randint(1, goods.sum)
            user = User.objects.filter(username=userId)[0]

            order_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            timeArray = time.strptime(order_time, "%Y-%m-%d %H:%M:%S")
            order = TransactionRecords()
            order.ids = createOrderIds(str(goods.id),timeArray,str(sellSum),str(user.username))
            order.Date = order_time
            order.goodsId = goods
            order.sum = sellSum
            order.Price = goods.preferentialPrice * sellSum
            order.preferential = goods.preferential
            order.sumPreferentialPrice = goods.preferentialPrice
            order.userId = user
            order.save()
            # 修改商品的售出与库存
            goods.sum = goods.sum - sellSum
            goods.soldSum = goods.soldSum + sellSum
            goods.save()
            dic['data'] = {
                'ids': order.ids,
                'date': order_time,
                'sum': sellSum,
                'price': order.Price,
                'preferential': order.preferential,
                'preferentialPrice': order.sumPreferentialPrice,
                'userId': {
                    'username': user.username,
                    'name': user.name
                }
            }
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有库存'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

# 生成交易单号
def createOrderIds(goodsId,date,sum,userId):
    date = time.strftime("%Y%m%d%H%M%S", date)
    return userId+date+goodsId+sum

# 获取订单数据
@csrf_exempt
def getOrderData(request):
    dic = {}
    if request.method == 'POST':
        typeId = int(request.POST.get('typeId'))
        username = request.POST.get('username')
        if typeId == -1:
            info = TransactionRecords.objects.all()
        else:
            info = TransactionRecords.objects.filter(goodsId__type__id=typeId)
        if username != '-1':
            info = info.filter(userId__username=username)
        if info:
            orderList = []
            for i in info:
                data = {
                    'picture': i.goodsId.picture.file.url,
                    'name': i.goodsId.name,
                    'date': str(i.Date)[:-6],
                    'type': i.goodsId.type.name,
                    'preferential': i.goodsId.preferential,
                    'price': i.Price,
                    'sum': i.sum,
                    'username': i.userId.name,
                    'unitId': i.goodsId.unitId.name
                }
                orderList.append(data)

            pageSize = int(request.POST.get('pageSize'))
            page = int(request.POST.get('pageId'))
            minSize = (page - 1) * pageSize
            maxSize = page * pageSize
            if maxSize >= len(orderList):
                dic['data'] = {
                    'orderList': orderList[minSize:],
                    'size': len(orderList)
                }
            else:
                dic['data'] = {
                    'orderList': orderList[minSize: maxSize],
                    'size': len(orderList)
                }

            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['data'] = {
                'orderList': [],
                'size': 0
            }
            dic['code'] = SUCCESS_CODE
            dic['message'] = '暂时没有订单'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

# 删除订单
@csrf_exempt
def deleteOrder(request):
    dic = {}
    if request.method == 'POST':
        pass
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})